package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.domain.Operator;
import cn.wolfcode.crm.mapper.OperatorMapper;
import cn.wolfcode.crm.util.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.util.Date;


public class ExtendFormAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private OperatorMapper operatorMapper;
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //设置编码规则
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json,charset=utf-8");

        //登录成功,响应JSONResult:{success:"true",msg:""}
        JsonResult jsonResult = new JsonResult();
        //将对象转换为json字符串
        String jsonString = new ObjectMapper().writeValueAsString(jsonResult);

        //将数据写出去
        PrintWriter writer = response.getWriter();
        writer.print(jsonString);
        Operator operator = (Operator) subject.getPrincipal();
        operatorMapper.updateLastLoginTime(new Date(),operator.getId());
        if(jsonResult.isSuccess()){
            int loginCount = operator.getLoginCount();
            loginCount=loginCount+1;
            operatorMapper.updateLoginCount(loginCount,operator.getId());

        }
        writer.flush();
        writer.close();
        //返回false,不需要执行后的filter
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //登录成功后的页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");
        JsonResult jsonResult = new JsonResult();
        if (e.getClass().getSimpleName().equals("UnknownAccountException")) {
            jsonResult = new JsonResult("账户不存在的");
        } else if (e.getClass().getSimpleName().equals("IncorrectCredentialsException")) {
            jsonResult = new JsonResult("密码错误");
        } else {
            jsonResult = new JsonResult("系统异常...");
        }
        try {
            String jsonString = new ObjectMapper().writeValueAsString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.print(jsonString);
            writer.flush();
            writer.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
